package 牛客剑指专题二刷.链表;

/**
 * 链表中倒数最后k个节点
 * 法1：2次遍历
 * 法2：用栈遍历，然后出栈k次
 * 法3：快慢指针，fast先行k步
 */
public class JZ22 {
    class ListNode{
        int val;
        ListNode next = null;
        ListNode(int val){
            this.val = val;
        }
    }
    public ListNode FindKthToTail (ListNode pHead, int k) {
        // write code here
        ListNode fast = pHead, slow = pHead;
        while(k-- > 0 ){
            if(fast == null) return null;
            fast = fast.next;
        }
        while(fast != null){
            fast = fast.next;
            slow = slow.next;
        }
        return slow;
    }
}
